/**
 * Created by no1 on 2015/8/28.
 */
'use strict';
var mysql = require('../mysql.js');
var C = require('../../config/index');
var F = require('../../common/function');
var MPosts = require('../../model/posts.js');
var MTags = require('../../model/tags.js');
var MUser = require('../../model/users.js');
var Mman = require('../../common/man.js');
var imgRule = require('../../common/imgRule.js');
var _ = require('underscore');
var _s = require('underscore.string');
var md5 = require('md5');
var request = require('koa-request');
var async_request = require('request');
var logstash = require('./../logFlow/logstash.js');
_.v = require('validator');
var getPostList = require("./getPostList.js").getPostList;

/**
 * @todo API31 帖子图片上传成功后的Callback
 * @param Env
 * @returns {*}
 */
exports.imgCallback = function*(Env, data) {

  // 是否内部调用
  let fields;
  let loginStatus = Env.I.loginStatus;

  //var loginStatus = yield F.isLogin(Env);
  if (!data) { // API 过了
    if (!loginStatus.status) {
      return F.returnMsg(401, '注册用户才能发帖', 3);
    }
    if (loginStatus.groupid == 4) { // gid=4 为禁止发言组
      return F.returnMsg(400, '用户已被限制发帖', 1);
    }
    fields = Env.I;
  } else { // 内部调用
    fields = data;
  }


  var act = fields.act;
  var return_act=9;
  if (act == 1) {//act为1时代表发图成功
    let check = yield F.check_post();
    let tid = parseInt(fields.tid);
    if (check == 0 || data) { // 无需审核 或 执行【通过审核】
      if (data) { // 执行【通过审核】
        var threadData = yield mysql.query('SELECT mt.uid,fid,mpc.post,mt.pid,status,mt.type FROM mh_thread mt INNER JOIN mh_post_content mpc ON mt.pid=mpc.pid WHERE mt.tid=? AND mt.checkflag=1', [tid]);
        if (threadData.length < 1) return F.returnMsg(400, '审核失败，不存在需要审核的帖子', 1);
      } else { // 无需审核
        var threadData = yield mysql.query('SELECT mt.uid,fid,mpc.post,mt.pid,status,mt.type FROM mh_thread mt INNER JOIN mh_post_content mpc ON mt.pid=mpc.pid WHERE mt.tid=?', [tid]);
        if (threadData.length < 1) return F.returnMsg(400, '发布失败', 1);
      }

      //判断是不是美容贴
      //if(parseInt(threadData[0].type)>0){
      //  return_act=12;
      //}
      //如果是不显示的帖子，则直接返回
      if(parseInt(threadData[0].status)==2){
        if (fields.apiVerNum == 1)
          fields.apiVerNum = 2;
        return yield getPostList(Env, {
          act: return_act,
          tid: tid,
          tokenkey: fields.tokenkey,
          apiVerNum: fields.apiVerNum
        });
      }

      let uid = threadData[0]['uid'];
      var key = C.redisPre.thread_user;
      key = _s.sprintf(key, parseInt(tid));
      var temp = yield F.redisCo.EXISTS(key);
      if (temp == 1 || data) {
        if(threadData[0].fid>0 || threadData[0].type>0){//日记帖
          if(threadData[0].fid == 0){//发表日记
            yield F.memberCount(threadData[0].uid, 'threads=threads+1,posts=posts+1,plasticthreads=plasticthreads+1,allplasticthreads=allplasticthreads+1');//更新用户发帖数
          }else{//更新日记
            yield F.memberCount(threadData[0].uid, 'threads=threads+1,posts=posts+1');//更新用户发帖数

            let tidArr = [];
            let daily_fid = threadData[0].fid;
            let daily_tid_arr = yield  mysql.query('SELECT tid from mh_thread where tid=? or fid=? ORDER BY tid ', [daily_fid, daily_fid]);
            if (daily_tid_arr.length > 0) {
              for (var i in daily_tid_arr) {
                tidArr.push(daily_tid_arr[i].tid);
              }
              var key = C.redisPre.thread_info;
              var expire = C.redisPre.thread_ttl;
              yield F.redisCo.mhincreasethreadfield(4, key, expire, 1, 'dailyNum', tidArr);//将所有缓存里面的日记篇数+1
            }
            mysql.query('update mh_thread_extend set dailyNum=dailyNum+1 where tid=?',daily_fid);
          }
        }else{//普通贴
          yield F.memberCount(threadData[0].uid, 'threads=threads+1,posts=posts+1');//更新用户发帖数
        }
        yield F.addDynamicInfo((F.isManager(loginStatus.groupid) ? -uid : uid), 1, tid, threadData[0]['pid']);//发帖写动态

        //删除缓存开始
        //key = C.redisPre.thread_user;
        //key = _s.sprintf(key, parseInt(tid));
        //F.redisClient.DEL(key);
        //删除缓存结束

        //更新标签热度开始
        var threadTag = yield mysql.query('SELECT tagsid,tagstype FROM mh_thread_tags WHERE tid=?', [tid]);
        for (var i in threadTag) {
          if (threadTag[i].tagstype == 1 || threadTag[i].tagstype == 4 || threadTag[i].tagstype == 5 || threadTag[i].tagstype == 6 || threadTag[i].tagstype == 99) {//标签
            mysql.query('UPDATE mh_tags SET tagcount=tagcount+1 WHERE tagid=?', [threadTag[i].tagsid]);//更新标签热度
            //更新标签信息开始
            var k1 = C.redisPre.tag_info;
            k1 = _s.sprintf(k1, parseInt(threadTag[i].tagsid), 1);
            var temp = yield F.redisCo.EXISTS(k1);
            if (temp == 1) {
              F.redisClient.HINCRBY(k1, 'tagcount', 1);//标签热度+1
            }
            //更新标签信息结束
          } else if (threadTag[i].tagstype == 2) {//用户
            var userInfo = yield F.returnUserInfo(threadTag[i].tagsid);
            var atuserisvest = F.isManager(parseInt(userInfo[0].groupid)) || F.isVest(threadTag[i].tagsid);//at用户是管理员跟马甲都是马甲
            var threadhostInfo = yield F.returnUserInfo(threadData[0].uid);


            yield F.addDynamicInfo(F.isManager(threadhostInfo[0].groupid) ? -threadData[0].uid : threadData[0].uid, atuserisvest ? -5 : 5, tid, parseInt(threadTag[i].tagsid));//帖子中标记用户写动态
            // 马甲用户不推送
            if (!F.isVest(parseInt(threadTag[i].tagsid))) {
              var result = yield mysql.queryOne('SELECT mu.os_type,mu.device_token,mui.pushpost,mui.pushdisturb FROM mh_user mu INNER JOIN mh_user_info mui ON mu.uid=mui.uid WHERE mu.uid=?', [parseInt(threadTag[i].tagsid)]);

              if (result && result['pushfriend'] == 1 && F.disturb(parseInt(result['pushdisturb']))) {
                var msg = _s.truncate(threadData[0].post, 27, '...');
                let nickname = yield mysql.queryOne('SELECT nickname FROM mh_user WHERE uid=?', [uid]);
                F.umengSendMsg(result['os_type'], result['device_token'], 6, {
                  nickname: nickname['nickname'],
                  tid: tid,
                  msg: msg
                });
              }
            }
          }
        }
        //更新标签热度结束
        //var uid=yield F.redisCo.GET(key);
        if (parseInt(uid) == parseInt(threadData[0].uid)) {
          if(parseInt(threadData[0].status)==0) {//如果帖子状态是无效则改成有效，如果是有效或者广告贴状态则不更改
            yield mysql.query('UPDATE mh_thread set `status`=1,checkflag=0 WHERE tid=?', [tid]);//更新帖子状态
            yield mysql.query('UPDATE mh_post set `status`=1,checkflag=0 WHERE pid=?', [threadData[0].pid]);//更新帖子状态
            let key = C.redisPre.thread_info;
            key = _s.sprintf(key,tid);
            F.redisClient.del(key);
          }
          //最新帖子列表写缓存开始
          var key = C.redisPre.lists_news;
          var expire = C.redisPre.lists_news_ttl;
          key = _s.sprintf(key, 0);
          var arr = [];
          arr[0] = key;
          arr.push(tid);
          arr.push(tid);
          yield F.redisCo.ZADD(arr);
          F.redisClient.expire(key, expire);
          //最新帖子写缓存结束

          //个人发帖写入缓存开始
          key = C.redisPre.lists_user;
          key = _s.sprintf(key, parseInt(uid));
          var tidArr = [];
          tidArr[0] = key;
          tidArr.push(tid);
          tidArr.push(tid);
          yield F.redisCo.ZADD(tidArr);
          F.redisClient.expire(key, expire);
          //个人发帖写入缓存结束

          //更新发帖人信息开始
          key = C.redisPre.user_info;
          key = _s.sprintf(key, parseInt(uid));
          var temp = yield F.redisCo.EXISTS(key);
          if (temp == 1) {
            F.redisClient.HINCRBY(key, 'threads', 1);//用户发帖数+1
            F.redisClient.HINCRBY(key, 'posts', 1);//用户回帖数+1
            if (threadData[0].type > 0 && threadData[0].fid == 0) {//整形帖
              F.redisClient.HINCRBY(key, 'plasticthreads', 1);//用户有效美容贴+1
              F.redisClient.HINCRBY(key, 'allplasticthreads', 1);//用户所有美容贴+1
            }
          }
          //更新发帖人信息结束

          //如果缓存帖子数超过了配置中lists_del_count则删除lists_del_count-lists_init_count项
          key = C.redisPre.lists_news;
          key = _.str.sprintf(key, 0);
          var cacheCount = yield F.redisCo.ZCARD(key);//取得缓存记录数
          if (cacheCount > parseInt(C.redisPre.lists_del_count)) {
            F.redisClient.ZREMRANGEBYRANK(key, 0, parseInt(C.redisPre.lists_del_count) - parseInt(C.redisPre.lists_init_count) - 1);//删除分数小的缓存
          }

          var gain = yield F.generateIntegralLog(uid, 3, tid);//发帖成功后获得积分
          if (data) { // 内部调用
            return F.returnMsg(200, '审核成功', 1);
          } else { // 用户正常调用
            if (fields.apiVerNum == 1)
              fields.apiVerNum = 2;
            return yield getPostList(Env, {
              act: return_act,
              tid: tid,
              tokenkey: fields.tokenkey,
              apiVerNum: fields.apiVerNum,
              addthread: 1,
              gain: gain
            });
          }
        } else {
          return F.returnMsg(400, '图片发布已经超时', 1);
        }
      } else {
        return F.returnMsg(400, '图片发布已经超时', 1);
      }
    } else {// 用户发帖，并需要审核
      mysql.query('UPDATE mh_thread set `checkflag`=1 WHERE tid=?', [tid]);//更新帖子状态
      mysql.query('UPDATE mh_post set `checkflag`=1 WHERE tid=? AND first=1', [tid]);//更新帖子状态
      //return F.returnMsg(200, '发布成功，等待审核', 1);
      if (fields.apiVerNum == 1)
        fields.apiVerNum = 2;
      return yield getPostList(Env, {
        act: return_act,
        tid: tid,
        tokenkey: fields.tokenkey,
        apiVerNum: fields.apiVerNum
      });
    }
  }
};
